<?php
/* $Id: admin.php 14 2009-04-11 17:40:34Z ronan $ */
//Basic idea is going to be have a link menu at the top with a bunch of GET additions to the page
//The page will just check what GET is used and pull up the relevant database table
$basesite=$_SERVER['PHP_SELF'];
require("common.php");
require("auth.php");
RequireUserLevel(array('admin', 'headproducer'));
require("header.php");
?>
<a href="admin.php?f=setstatus">Set User Status</a>
<?php
if($userLevel=='admin'){
?>
 | <a href="admin.php?f=view&cat=items">Items</a> | <a href="admin.php?f=view&cat=users">Users</a> | <a href="admin.php?f=view&cat=orders">Orders</a> | <a href="admin.php?f=view&cat=blueprints">Blueprints</a> | <a href="admin.php?f=updateallprices&cat=all">Update All Prices</a><br /><br />
<?php }
if($userLevel=='admin') {
if(isset($_POST['updateminprices'])) {
	$minerals = Query("SELECT * FROM minerals ORDER BY price ASC");
	while($l = mysql_fetch_array($minerals)) {
		Query("UPDATE minerals SET price='".$_POST[$l['typeID'].'_price']."' WHERE typeID='".$l['typeID']."' LIMIT 1");
	}
	echo "Prices updated";
	$f="updateprices";$cat="minerals";
}
if(isset($_GET['addblueprint'])) {
	$typeID=$_GET['typeid'];
	$price=$_GET['price'];
	$ME=$_GET['me'];
	$PE=$_GET['pe'];
	$runs=$_GET['runs'];
	$numAvailable=$_GET['numavailable'];
	$item=Query("SELECT * FROM items WHERE typeID='$typeID' LIMIT 1");
	$typeName=mysql_result($item,0,'typeName');
	$marketGroupID=mysql_result($item,0,'marketGroupID');
	$result = Query("INSERT INTO blueprints(typeID, marketGroupID, typeName, price, ME, PE, runs, numAvailable) VALUES('$typeID', '$marketGroupID', '$typeName', '$price','$ME','$PE','$runs','$numAvailable')");
	$f="view";
	$cat="blueprints";
}

if(isset($_GET['updateblueprint'])) {
	$id=$_GET['id'];
	$typeID=$_GET['typeid'];
	$price=$_GET['price'];
	$ME=$_GET['me'];
	$PE=$_GET['pe'];
	$runs=$_GET['runs'];
	$numAvailable=$_GET['numavailable'];
	$item=Query("SELECT * FROM items WHERE typeID='$typeID' LIMIT 1");
	$typeName=mysql_result($item,0,'typeName');
	$marketGroupID=mysql_result($item,0,'marketGroupID');
	$result = Query("UPDATE blueprints SET typeID='$typeID', marketGroupID='$marketGroupID', typeName='$typeName', price='$price',ME='$ME',PE='$PE',runs='$runs',numAvailable='$numAvailable' WHERE id='$id' LIMIT 1");
	$f="view";
	$cat="blueprints";
}
//IF WE'RE UPDATING BUILDABLE STATUS, A UPDATEBUILDABLE WILL =1
if(isset($_GET['updatebuildable'])) {
	$hasTypes=$_GET['hastypes'];
	$isBuildable=$_GET['isbuildable'];
	if($hasTypes) { //ITEM
		$typeID=$_GET['id'];
		if($typeID=='all') {
			$result = Query("UPDATE items SET isBuildable='$isBuildable' WHERE marketGroupID='".$_GET['marketgroup']."'");
		} else $result = Query("UPDATE items SET isBuildable='".($isBuildable?0:1)."' WHERE typeID='$typeID' LIMIT 1");
	} else { //MARKETGROUP
		$marketGroupID=$_GET['id'];
		$result = Query("UPDATE invMarketGroups SET isBuildable='".($isBuildable?0:1)."' WHERE marketGroupID='$marketGroupID' LIMIT 1");
	}
	echo "Updated isBuildable status.<br />\n";
	$f="view";
	$cat="items";
}
//IF WE'RE UPDATING A MARKETGROUP PRICE MODIFIER, AN UPDATEMARKETPRICEMOD WILL =1'
if(isset($_GET['updatemarketpricemod'])) {
	$newMod = $_GET['newmod'];
	$marketGroupID=$_GET['id'];
	$result = Query("UPDATE invMarketGroups SET priceMod='$newMod' WHERE marketGroupID='$marketGroupID' LIMIT 1");
	echo "Updated price modifier on marketGroupID $marketGroupID to $newMod \n<br />\n<br />";
	$f="view";
	$cat="items";
}
//IF WE'RE UPDATING USEMINERALPRICES STATUS, A UPDATEUSEMINERALPRICES WILL =1
if(isset($_GET['updateusemineralprices'])) {
	$hasTypes=$_GET['hastypes'];
	$useMineralPrices=$_GET['usemineralprices'];
	$typeID=$_GET['id'];
	if($typeID=='all') {
		$result = Query("UPDATE items SET useMineralPrices='$useMineralPrices' WHERE marketGroupID='".$_GET['marketgroup']."'");
	} else $result = Query("UPDATE items SET useMineralPrices='".($useMineralPrices?0:1)."' WHERE typeID='$typeID' LIMIT 1");
	echo "Updated useMineralPrices status.<br />\n";
	$f="view";
	$cat="items";
}
//IF WE'RE UPDATING PRICE STATUS, A UPDATEPRICE WILL =1
if(isset($_GET['updateprice'])) {
	$hasTypes=$_GET['hastypes'];
	$price=$_GET['price'];
	$quantityModifier=$_GET['quantitymodifier'];
	if($hasTypes) { //ITEM
		$typeID=$_GET['typeid'];
		$result = Query("UPDATE items SET price='$price', quantityModifier='$quantityModifier' WHERE typeID='$typeID' LIMIT 1");
	} else { 
		echo "You stupid thing, marketgroups don't have prices! wtf??";
	}
	echo "Updated price<br /><br />\n\n";
	$f="view";
	$cat="items";
}
if(isset($_POST['updateitemsall'])) {
	$hasTypes=$_POST['hastypes'];
	$numrows=$_POST['numrows'];
	$isBuildableArray = (isset($_POST['isbuildable'])&&is_array($_POST['isbuildable'])?$_POST['isbuildable']:array());
	$isSpecialOrderableArray = (isset($_POST['isspecialorderable'])&&is_array($_POST['isspecialorderable'])?$_POST['isspecialorderable']:array());
	$useMineralPricesArray = (isset($_POST['usemineralprices'])&&is_array($_POST['usemineralprices'])?$_POST['usemineralprices']:array());
	if($hasTypes) { //ITEM
		for($i=0;$i<$numrows;$i++) {
			$price=$_POST[$i.'_price'];
			$quantityModifier=$_POST[$i.'_quantitymodifier'];
			$numAvailable=$_POST[$i.'_availability'];
			$typeID=$_POST[$i.'_typeid'];
			$isBuildable=(in_array($i,$isBuildableArray)?1:0);
			$isSpecialOrderable=(in_array($i,$isSpecialOrderableArray)?1:0);
			$useMineralPrices=(in_array($i,$useMineralPricesArray)?1:0);
			$result = Query("UPDATE items SET isSpecialOrderable='$isSpecialOrderable', isBuildable='$isBuildable', useMineralPrices='$useMineralPrices', price='$price', quantityModifier='$quantityModifier', numAvailable='$numAvailable' WHERE typeID='$typeID' LIMIT 1");
		}
	} else { 
		echo "You stupid thing, marketgroups don't have prices! wtf??";
	}
	echo "Updated data<br /><br />\n\n";
	$f="view";
	$cat="items";
}

//IF WE'RE UPDATING NUMAVAILABLE STATUS, A UPDATEAVAILABILITY WILL =1
if(isset($_GET['updateavailability'])) {
	$hasTypes=$_GET['hastypes'];
	$numAvailable=$_GET['availability'];
	if($hasTypes) { //ITEM
		$typeID=$_GET['typeid'];
		$result = Query("UPDATE items SET numAvailable='$numAvailable' WHERE typeID='$typeID' LIMIT 1");
	} else { 
		echo "You stupid thing, marketgroups don't have availabilities! wtf??";
	}
	echo "Updated availability!<br /><br />\n\n";
	$f="view";
	$cat="items";
}
//IF WE'RE DELETING SOMETHING, A DELETETYPE WILL HAVE BEEN SPECIFIED'
if(isset($_POST['deletetype'])) {
	$deletetype = $_POST['deletetype'];	
	$id = $_POST['id'];
	$result=Query("DELETE FROM $deletetype WHERE ".$idkeylist[$deletetype]."='$id' LIMIT 1");
	echo "Record deleted.<br /><br />\n\n";
	$f="view";
	$cat=$deletetype;
}
//IF WE'RE ADDING SOMETHING, AN ADDTYPE WILL HAVE BEEN SPECIFIED
if(isset($_POST['addtype'])) {
	$addtype=$_POST['addtype'];
	//Fill an array with the relevant field titles...
	$fields=array();
	$dqueryr=Query("DESC $addtype");
	while($line = mysql_fetch_array($dqueryr)) {
		array_push($fields, $line['Field']);
	}	
	//Generate the add query
	$q= "INSERT INTO $addtype (";
	foreach($fields as $field) {
		if(isset($_POST['0_'.$field]) && $field!=$idkeylist[$edittype]) {
			if(isset($commatemp)) $q.=', '; else $commatemp=true;
			$q.=$field;
		}
	}
	$q.=") VALUES (";
	unset($commatemp);
	foreach($fields as $field) {
		if(isset($_POST['0_'.$field]) && $field!=$idkeylist[$edittype]) {
			//Deal with passwords - blank = don't change, if we do change, we need to PASSWORD() it'
			if(array_key_exists($field, $passwordkeys)) { 
				if($_POST['0_'.$field]=='') continue;
				if(isset($commatemp)) $q.=', '; else $commatemp=true;
				$q.="PASSWORD('".$_POST['0_'.$field]."')";
				continue;
			}
			if(isset($commatemp)) $q.=', '; else $commatemp=true;
			$q.="'".$_POST['0_'.$field]."'";
		}
	}
	unset($commatemp);
	$q.=")";
	$result = Query($q);
	echo "Added 1 record.<br /><br />\n\n";
	$f="view";
	$cat=$addtype;
}
//IF WE'RE UPDATING THE DATABASE, AN EDITTYPE WILL HAVE BEEN SPECIFIED
if(isset($_POST['edittype'])) {
	$edittype = $_POST['edittype'];//which table to edit
	//Fill an array with the relevant field titles...
	$fields=array();
	$dqueryr=Query("DESC $edittype");
	while($line = mysql_fetch_array($dqueryr)) {
		array_push($fields, $line['Field']);
	}
	for($i=0;$i<$_POST['numrows'];$i++) {
		//Generate the update query
		$q="UPDATE $edittype SET ";
		foreach($fields as $field) {
			if(isset($_POST[$i.'_'.$field]) && $field!=$idkeylist[$edittype]) {
				//Deal with passwords - blank = don't change, if we do change, we need to PASSWORD() it'
				if(array_key_exists($field, $passwordkeys)) { 
					if($_POST[$i.'_'.$field]=='') continue;
					if(isset($commatemp)) $q.=', '; else $commatemp=true;
					$q.=$field."=PASSWORD('".$_POST[$i.'_'.$field]."')";
					continue;
				}
				if(isset($commatemp)) $q.=', '; else $commatemp=true;
				$q.=$field."='".$_POST[$i.'_'.$field]."'";
			}
		}
		unset($commatemp);
		$q.=" WHERE ".$idkeylist[$edittype]."='".$_POST[$i.'_'.$idkeylist[$edittype]]."' LIMIT 1";
		$result = Query($q);
	}
	echo "Updated database. (".$_POST['numrows']." record".($_POST['numrows']==1?'':'s').")<br /><br />\n\n";
	$f="view";
	$cat=$edittype;
}

//Now, if we AREN'T updating the database...'
if(isset($_GET['f']) && isset($_GET['cat'])) {
	$f=$_GET['f'];
	$cat=$_GET['cat'];	
}
if(!isset($f) || !isset($cat)){ //No function chosen, just leave it at the base menu (generated at top)
	if(!isset($_GET['f']) || $_GET['f']!='setstatus') {
		require("footer.php"); exit;
	}
	$f="setstatus";
	$cat="none";
}
if($f=='updateallprices') { 
	echo '<font color="red">WARNING: YOU ARE ABOUT TO REPLACE PRICES ON <b><u><i>ALL ITEMS FLAGGED WITH useMineralPrices=1</i></u></b> WITH ESTIMATIONS BASED ON MINERAL COSTS. ALL POSSIBLE PRICES WILL BE <b><u><i>REPLACED</i></u></b>. THIS MAY GENERATE THOUSANDS UPON THOUSANDS OF DATABASE QUERIES, SOME VERY LARGE. TO CONTINUE, GO <a href="admin.php?f=updateallpricesconfirm&cat=none">HERE</a> AND CHANGE cat=none TO cat=0 IN THE URL.<br /><br /></font>Alternately, to just change the mineral prices, go <a href="admin.php?f=updateprices&cat=minerals">here</a>.';
	require("footer.php");
	exit;
}
if($f=='updateprices'&&$cat=='minerals') {
	$minerals = Query("SELECT * FROM minerals ORDER BY price ASC");
	echo "<form method=\"POST\" action=\"admin.php\">".generateHiddenFields(array("updateminprices"=>1))."<table>";
	while($l=mysql_fetch_array($minerals)) {
		echo "<tr>\t" .
				"<td><img width=\"$imgsize\" height=\"$imgsize\" src=\"".getGraphicPath($l['graphicID'])."\" /></td>\t" .
				"<td>".$l['typeName']."</td>\t" .
				"<td><input type=\"text\" name=\"".$l['typeID']."_price\" value=\"".$l['price']."\" /></td>" .
				"</tr>\n";
	}
	echo "</table><input type=\"submit\" value=\"Update Mineral Prices\" /></form>";
	require("footer.php");
	exit;
}
if($f=='updateallpricesconfirm' && $cat!='none') {
	echo "If this operation times out, change 0 to whatever item index you wish to start at.<br /><br />\n\n";
	
	//Recursive function looks are current market group, checks for a modifier set to it, and then either applies it to the group or (if it has no items) calls itself on all groups in it
	function nextMarketLevel(&$marketArray, $cmid, $cmod) {
		$currMarketGroups = Query("SELECT * FROM invMarketGroups WHERE parentGroupID='$cmid'");
		while($line=mysql_fetch_array($currMarketGroups)) {
			$cmod *= $line['priceMod'];
			if($line['hasTypes']==0) {
				nextMarketLevel($marketArray, $line['marketGroupID'], $cmod);
			} else {
				$marketArray[$line['marketGroupID']]=$cmod;
			}
		}
	}
	$baseMarketGroups=Query("SELECT * FROM invMarketGroups WHERE parentGroupID IS NULL");
	$marketModArray = array(); //Will store a mod value for EVERY marketgroup with items in it. big array.
	while($line=mysql_fetch_array($baseMarketGroups)) {
		$cmod = $line['priceMod'];
		nextMarketLevel($marketModArray, $line['marketGroupID'], $cmod);
	}	
	$allitems=Query("SELECT * FROM items WHERE typeID>='$cat' AND useMineralPrices=1");
	$minerals=Query("SELECT * FROM minerals ORDER BY price ASC LIMIT 8");
	$mineralprices=array();
	$i=0;
	while($l=mysql_fetch_array($minerals)) {
		$mineralprices[$l['typeID']]=$l['price'];
	}
	while($l=mysql_fetch_array($allitems)) {
		$newprice=0;
		$bp = Query("SELECT * FROM items WHERE typeName='".$l['typeName']." Blueprint' LIMIT 1");
		if(mysql_num_rows($bp)==0) { //NO BLUEPRINT FOUND
			echo "Warning: No blueprint found for item '".$l['typeName']."' (typeID: ".$l['typeID'].") - using reprocess values instead of build values<br />\n";
			$mineralqty=Query("SELECT * FROM tl2materialsfortypewithactivity WHERE typeID='".$l['typeID']."' AND ((requiredTypeID<=40 AND requiredTypeID>=34) OR requiredTypeID=11399 OR requiredTypeID=16275) ORDER BY quantity DESC LIMIT 8");
		}
		else $mineralqty=Query("SELECT * FROM tl2materialsfortypewithactivity WHERE activity=1 AND typeID='".mysql_result($bp,0,'typeID')."' AND ((requiredTypeID<=40 AND requiredTypeID>=34) OR requiredTypeID=11399 OR requiredTypeID=16275) ORDER BY quantity DESC LIMIT 8");
		if(!mysql_num_rows($mineralqty)) continue;
		$i++;
		$cmod=$marketModArray[$l['marketGroupID']];
		while($il = mysql_fetch_array($mineralqty)) {
			$newprice+= round($il['quantity'] * $l['quantityModifier'] * $mineralprices[$il['requiredTypeID']] * 1.1 * $cmod, 2);
		}
		Query("UPDATE items SET price='$newprice' WHERE typeID='".$l['typeID']."' LIMIT 1");
	}
	echo "Completed price update ($i rows affected).\n";
	require("footer.php");
	exit;
}
if($cat!='none'){
	$idkey=$idkeylist[$cat];
}
if($f=='view' && $cat=='items') {
	$marketgroup=isset($_GET['marketgroup'])?$_GET['marketgroup']:(isset($_POST['marketgroup'])?$_POST['marketgroup']:null);
	$hastypes=isset($_GET['hastypes'])?$_GET['hastypes']:(isset($_POST['hastypes'])?$_POST['hastypes']:null);
	echo getMarketPath($marketgroup, true) . "<br /><br />\n\n";
	echo getMarketGroup($marketgroup, $hastypes, true);
	require("footer.php");
	exit;
}
if($f=='view' && $cat=='blueprints') {
	echo getBlueprintMarketPath('all', true) . "<br /><br />\n\n";
	echo getBlueprintMarketGroup('all', 1, true);
	echo "<br />\n".generateButton("Add Blueprint", "GET", array("f"=>"add", "cat"=>"blueprints"));
	require("footer.php");
	exit;
}
if($f=='view' && $cat=='orders') {
	$start=(isset($_GET['start'])?$_GET['start']:0);
	$perPage=(isset($_GET['perpage'])?$_GET['perpage']:50);
	$orderby=(isset($_GET['orderby'])?$_GET['orderby']:$idkey);
	$ad=(isset($_GET['ad'])?$_GET['ad']:'ASC');
	$table = Query("SELECT * FROM $cat WHERE status<>'completed' AND status<>'in cart' ORDER BY $orderby $ad LIMIT $start, $perPage");
	echo "Click the ID number to edit the row.";
	//echo " <a href=\"admin.php?f=multedit&cat=$cat\">Click here to edit all at once.</a><br /><br />";
	//begin tableheader
	echo "<table border=0 cellspacing=0 cellpadding=2><tr>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=id&ad=".($orderby=='id'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">ID</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=timePlaced&ad=".($orderby=='timePlaced'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Placed</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=timeCompleted&ad=".($orderby=='timeCompleted'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Completed</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=typeName&ad=".($orderby=='typeName'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Item</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=quantity&ad=".($orderby=='quantity'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Qty</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=pricePerUnit&ad=".($orderby=='pricePerUnit'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Per Unit</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=priceTotal&ad=".($orderby=='priceTotal'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Total</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=customerName&ad=".($orderby=='customerName'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Customer</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=producerName&ad=".($orderby=='producerName'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Producer</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=status&ad=".($orderby=='status'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Status</a></b></td>" .
			"<td><b><a href=\"admin.php?f=view&cat=orders&orderby=usingStock&ad=".($orderby=='usingStock'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Type</a></b></td>" .
			"</tr>";
	//end tableheader
	while ($sa = mysql_fetch_array($table, MYSQL_ASSOC)) {
		if(!is_array($sa)) return "<tr><td>No row data</td></tr>\n";
		echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">"); $bgcolor= !$bgcolor;
		foreach($sa as $key=>$col) {
			if($idkey==$key) {
				echo "\t<td><a href=\"".$_SERVER['PHP_SELF'].'?f=edit&cat='.$cat.'&id='.$col."\">$col</a></td>\t";
				continue;
			} else if($key=='typeID' || $key=='customerID' || $key=='producerID') { continue;
			} else if($key=='timePlaced' || $key=='timeCompleted') { echo "\t<td>".dateTime($dateTimeFormat, $col)."</td>\t"; continue;
			} else if($key=='status') { echo "\t<td>".ucwords($col)."</td>\t"; continue;
			} else if($key=='usingStock') { echo "\t<td>".getColoredType($col)."</td>\t";
			} else if($ingame && ($key=='producerName' || $key=='customerName')) { echo "\t<td>".evemail($col)."\t"; continue;
			} else {echo "\t<td>$col</td>\t";}
		}
		echo "\t<td><a href=\"".$_SERVER['PHP_SELF']."?f=delete&cat=$cat&id=".$sa[$idkey]."\"><font color=\"red\">DEL</font></a></td>\t";
		echo "\t</tr>\n";	
	}
	echo toTableFooter();
	echo generateButton("Add", "GET", array("f"=>"add", "cat"=>$cat));
	echo "<form method=\"GET\" action=\"admin.php\">".generateHiddenFields(array("f"=>"view","cat"=>$cat))."Show <input type=\"text\" size=\"4\" name=\"perpage\" value=\"$perPage\" /> rows starting from row <input type=\"text\" size=\"4\" name=\"start\" value=\"$start\" />: <input type=\"submit\" value=\"Show\" /></form>";
	require("footer.php");
	exit;
}
if($f=='view' && $cat=='users') {
	$start=(isset($_GET['start'])?$_GET['start']:0);
	$perPage=(isset($_GET['perpage'])?$_GET['perpage']:50);
	$orderby=(isset($_GET['orderby'])?$_GET['orderby']:$idkey);
	$ad=(isset($_GET['ad'])?$_GET['ad']:'ASC');
	$table = Query("SELECT * FROM users ORDER BY $orderby $ad LIMIT $start, $perPage");
	echo "Click the ID number to edit the row.";
	//echo "<a href=\"admin.php?f=multedit&cat=$cat\">Click here to edit all at once.</a><br /><br />";
	echo "<table border=0 cellspacing=0 cellpadding=2><tr>";
	$fields=array();
	$dqueryr=Query("DESC $cat");
	while($line = mysql_fetch_array($dqueryr)) {
		$fields[$line['Field']]='';
	}
	foreach($fields as $key=>$col) {
		echo "\t<td><b><a href=\"admin.php?f=view&cat=users&orderby=$key&ad=".($orderby==$key?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">$key</a></b></td>\t";
	}
	echo "</tr>\n";
	while ($sa = mysql_fetch_array($table, MYSQL_ASSOC)) {
		if(!is_array($sa)) return "<tr><td>No row data</td></tr>\n";
		echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">"); $bgcolor= !$bgcolor;
		foreach($sa as $key=>$col) {
			if($idkey==$key) {
				echo "\t<td><a href=\"".$_SERVER['PHP_SELF'].'?f=edit&cat=users&id='.$col."\">$col</a></td>\t";
			} else if($key=='name') {echo "\t<td>".evemail($col)."</td>\t"; continue;}
			else {echo "\t<td>$col</td>\t";}
		}
		echo "\t<td><a href=\"".$_SERVER['PHP_SELF']."?f=delete&cat=users&id=".$sa[$idkey]."\"><font color=\"red\">DEL</font></a></td>\t";
		echo "\t</tr>\n";
	}
	echo "</table>\n";
	echo generateButton("Add", "GET", array("f"=>"add", "cat"=>$cat));
	echo "<form method=\"GET\" action=\"admin.php\">".generateHiddenFields(array("f"=>"view","cat"=>$cat))."Show <input type=\"text\" size=\"4\" name=\"perpage\" value=\"$perPage\" /> rows starting from row <input type=\"text\" size=\"4\" name=\"start\" value=\"$start\" />: <input type=\"submit\" value=\"Show\" /></form>";
	require("footer.php");
	exit;
}
if($f=='add' && $cat!='blueprints'){
	$fieldsaskeys=array();
	$dqueryr=Query("DESC $cat");
	while($line = mysql_fetch_array($dqueryr)) {
		$fields[$line['Field']]='';
	}
	echo toEditableTableHeader($fields, array("numrows"=>1, "addtype"=>$cat), true, $idkeylist[$cat]);
	echo toEditableTableRow($fields, $idkeylist[$cat], "add&cat=$cat", 0, true);
	echo toEditableTableFooter("Add item");
	require("footer.php");
	exit;	
}
if($f=='add' && $cat=='blueprints') {
	echo "Choose a type of blueprint to add:<br /><br />\n\n";
	echo getBlueprintMarketPath(isset($_GET['marketgroup'])?$_GET['marketgroup']:null, true) . "<br /><br />\n\n";
	echo getBlueprintMarketGroup(isset($_GET['marketgroup'])?$_GET['marketgroup']:null, isset($_GET['hastypes'])?$_GET['hastypes']:null, true);
	require("footer.php");
	exit;
}
if($f=='delete'){
	if(isset($_GET['id'])) $id=$_GET['id'];
	else {echo "You broke it! No id to delete!"; require("footer.php"); exit; }
	$table = Query("SELECT * FROM $cat WHERE ".$idkeylist[$cat]."='$id' LIMIT 1");
	$line = mysql_fetch_array($table, MYSQL_ASSOC);
	echo "You have chosen to delete the following record:<br /><br />\n\n";
	echo toTableHeader($cat);
	echo toTableRow($line, $cat);
	echo toTableFooter();
	echo "\n\n<br /><b><font color=\"red\">Are you sure you want to delete this record?</font></b> ".
		generateButton("Yes", "POST", array("id"=>$id, "deletetype"=>$cat))." ".
		generateButton("No", "GET", array("f"=>"view", "cat"=>$cat));
	require("footer.php");
	exit;
}
if($f=='edit') {
	if(isset($_GET['id'])) $id=$_GET['id'];
	else {echo "You broke it! No id to edit!"; require("footer.php"); exit; }
	$table = Query("SELECT * FROM $cat WHERE $idkey=$id LIMIT 1");
	$line = mysql_fetch_array($table, MYSQL_ASSOC);
	echo toEditableTableHeader($line, array("numrows"=>1, "edittype"=>"$cat"));
	echo toEditableTableRow($line, $idkey, "edit&cat=$cat", 0);
	echo toEditableTableFooter();
	require("footer.php");
	exit;
}
if($f=='multedit') {
	$table = Query("SELECT * FROM $cat");
	echo "Click the ID number to edit only that row. <font color=\"red\">WARNING - this can generate a MASSIVE number of database queries - it will make one query for each row!</font><br /><br />";
	$i=0;
	$line = mysql_fetch_array($table, MYSQL_ASSOC);
	echo toEditableTableHeader($line, array("numrows"=>mysql_num_rows($table), "edittype"=>"$cat"));
	do {
		echo toEditableTableRow($line, $idkey, "edit&cat=$cat",$i);
    	$i++;
	} while ($line = mysql_fetch_array($table, MYSQL_ASSOC));
	echo toEditableTableFooter();
	require("footer.php");
	exit;
}
} //END VERIFY ADMIN
if(!empty($_GET['f']) && $_GET['f']=='setstatus') {
	echo "<br /><br />Enter a name to adjust their status as a producer.<br /><br />";
	echo "<form method=\"GET\" action=\"admin.php\">".generateHiddenFields(array('f'=>'setstatus'))."<input type=\"text\" size=\"20\" name=\"q\" /><input type=\"submit\" value=\"Search\" /></form><br />\n";
	if(!empty($_GET['user'])) {
		$userIDnum=addslashes($_GET['user']);
		$newUserLevel=addslashes($_GET['newlevel']);
		$result=Query("UPDATE users SET userLevel='$newUserLevel' WHERE id='$userIDnum' LIMIT 1");
		echo "Updated user number $userIDnum";
	} 
	if(!empty($_GET['q'])) {
		$q=addslashes($_GET['q']);
		$userResult=Query("SELECT * FROM users WHERE name='$q' LIMIT 1");
		if(mysql_num_rows($userResult)==0) {
			echo "No user found with name $q";
		} else {
			$u=mysql_fetch_array($userResult, MYSQL_ASSOC);
			echo $u['name'].": User is currently a <b>".$u['userlevel']."</b>.<br /><br />";
			if($u['userlevel']=='admin' || $u['userlevel']=='headproducer') echo "This user has too high a level to edit from here.";
			else {
				echo "<form method=\"GET\" action=\"admin.php\">".generateHiddenFields(array('f'=>'setstatus','user'=>$u['id'])) .
				"<select name=\"newlevel\">";
				$levels = array('user', 'producer', 'producertrader', 'trader');
				foreach($levels as $level) {
					echo '<option value="'.$level.'"'.($u['userlevel']==$level?' selected':'').'>'.$level.'</option>';
				}
				echo "</select><br /><input type=\"submit\" value=\"Update\" /></form>";
			}
		}
	}
	require("footer.php");
	exit;
}
require("footer.php");
exit;
?>></form>";
			}
		}
	}
	require("footer.php");
	exit;
}
require("footer.php");
exit;
?>